package com.adu.action;
/**
 * 使用Struts2框架，来接收上传的文件
 * @author marlondu
 */
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class UploadAction extends SuperAction{
	private static final long serialVersionUID = 1L;
	
	private File file;			//要上传的文件对象,在客户端可以使用param_file参数设置
	private String fileName;	//文件名,在客户端可以使用param_fileName参数设置
	private String contentType;	//文件类型
	public String getFileName() {
		return fileName;
	}
	public void setFileName(String fileName) {
		this.fileName = fileName;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public File getFile() {
		return file;
	}
	public void setFile(File file) {
		this.file = file;
	}

	public String upload(){
		String savePath = this.application.getRealPath("/WEB-INF/upload");
		System.out.println(savePath);
		File folder = new File(savePath);
		if(!folder.exists()||!folder.isDirectory()){
			System.out.println("目录不存在，创建"+savePath);
			folder.mkdir();
		}
		System.out.println("正在上传文件:"+fileName);
		try {
			//创建输入流，用于从file对象读出数据
			InputStream ins = new FileInputStream(file);
			//创建输出文件对象
			File toFile = new File(savePath,fileName);
			//创建输出流，用于向toFile写入数据
			OutputStream ous = new FileOutputStream(toFile);
			byte[] buff = new byte[2048];
			int length = 0;
			while((length=ins.read(buff))>0){//读取数据
				ous.write(buff, 0, length);//写入本地
			}
			ous.close();
			ins.close();
			System.out.println("上传成功！");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
}
